<template>
  <div>
    <div class="header">

      <div class="page-header">
        <el-page-header @back="goBack" content="用户管理">
        </el-page-header>
      </div>

      <el-button type="success" icon="el-icon-plus" @click="addData" size="small"
                 style="margin-top:10px;margin-left: 20px">新增用户
      </el-button>
      <div class="search">
        <el-input v-model="pageRequest.key" style="width: 200px;margin-right: 10px" placeholder="按姓名查找"
                  size="small"></el-input>
        <el-button type="primary" icon="el-icon-search" size="small" @click="getUserList">搜索</el-button>
      </div>
    </div>
    <el-card class="box-card" shadow="always">
      <template>
        <el-table
            :header-cell-style="{color:'#333',fontFamily:'MicrosoftYaHeiUI',fontSize:'14px',fontWeight:900}"
            size="mini"
            :data="userList"
            style="width: 100%">
          <!--                    <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>-->
          <el-table-column prop="avatar" width="80" label="头像">
            <template slot-scope="scope">
              <el-image
                  style="width: 30px; height: 30px"
                  :src="scope.row.avatar"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="用户名" width="100">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.userName }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="nickName" label="姓名" width="100"></el-table-column>
          <el-table-column prop="password" :show-overflow-tooltip='true' width="100"
                           label="密码"></el-table-column>
          <el-table-column prop="roleNameList" width="100" label="用户角色">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="mini" v-for="roleName of scope.row.roleNameList">{{ roleName }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="status" width="100" label="账号状态">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium"
                        :type="scope.row.status === '0' ? 'success' : 'danger'">
                  {{ formatStatus(scope.row) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="email" width="135" label="邮箱"></el-table-column>
          <el-table-column prop="phoneNumber" width="120" label="手机号"></el-table-column>
          <el-table-column prop="sex" width="100" label="用户性别">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                {{ scope.row.sex === '0' ? '男' : '女' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createBy" width="120" label="创建人ID"></el-table-column>
          <el-table-column prop="createTime" width="150" label="创建时间"></el-table-column>
          <el-table-column prop="updateBy" width="100" label="更新人ID"></el-table-column>
          <el-table-column prop="updateTime" width="150" label="更新时间"></el-table-column>
          <!--                    <el-table-column prop="delFlag" width="100" label="删除标志"></el-table-column>-->
          <el-table-column
              fixed="right"
              label="操作"
              width="200">
            <template slot-scope="scope">
              <el-button :disabled="scope.row.userName === 'admin' " @click="updateRoleData(scope.row)"
                         icon="el-icon-setting" type="text"
                         size="mini">分配角色
              </el-button>
              <el-button :disabled="scope.row.userName === 'admin' " @click="updateData(scope.row)"
                         icon="el-icon-edit" type="text" size="mini">修改
              </el-button>
              <el-button :disabled="scope.row.userName === 'admin' "
                         @click="deleteData(scope.row.userId,scope.row.userType)" icon="el-icon-delete"
                         type="text"
                         size="small">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <div class="block">
        <el-pagination
            style="float: right"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageRequest.pageNum"
            :page-sizes="[10, 50, 100, 200]"
            :page-size="pageRequest.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageResult.total">
        </el-pagination>
      </div>
    </el-card>
    <div>
      <el-dialog
          width="830px"
          top="3vh"
          :title="operate.title"
          :rules="userRules"
          ref="form"
          @close="resetForm('form')"
          :visible.sync="dialogFormVisible">
        <el-form :inline="true" :model="form" ref="form" :rules="userRules" style="padding: 0px 50px"
                 size="small">

          <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
            <el-input
                v-model="form.userName"
                autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="姓名" :label-width="formLabelWidth" prop="nickName">
            <el-input
                v-model="form.nickName"
                autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
            <el-input
                type="password"
                v-model="form.password"
                autocomplete="off"></el-input>
          </el-form-item>


          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input
                v-model="form.email"
                autocomplete="off"></el-input>
          </el-form-item>


          <el-form-item label="电话" :label-width="formLabelWidth" prop="phoneNumber">
            <el-input
                v-model="form.phoneNumber"
                autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择">
              <el-option
                  v-for="item in sexOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="头像" :label-width="formLabelWidth">
            <el-upload
                class="upload-demo"
                :auto-upload="false"
                ref="upload"
                :action="uploadUrl"
                :on-change="handleChange"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>


          <el-form-item label="用户状态" :label-width="formLabelWidth" prop="status">
            <el-switch
                v-model="form.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="启用"
                inactive-text="禁用"
                active-value="0"
                inactive-value="1">
            </el-switch>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel" size="medium">取 消</el-button>
          <el-button type="primary" @click="operate.opType === 0?addUser('form'):updateUser()"
                     size="medium">确 定
          </el-button>
        </div>
      </el-dialog>

      <el-dialog
          width="550px"
          top="3vh"
          title="分配角色"
          :visible.sync="dialogCheckBoxVisible">
        <el-checkbox-group v-model="grantRoleParams.roleIdList">
          <el-checkbox :label="item.roleId" v-for="item in roleAllList" :key="item.roleId">
            {{ item.roleName }}
          </el-checkbox>
        </el-checkbox-group>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancelDialogCheckBox" size="medium">取 消</el-button>
          <el-button type="primary" @click="updateUserRole" size="medium">确 定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {deleteUser, getUserList, updateUser, addUser, grantRole} from "@/api/user";
import {getRoleAllList} from "@/api/role";
import MessageUtil from "../../utils/MessageUtil";
import md5 from 'js-md5';
import DeepCopyUtil from "@/utils/DeepCopyUtil";

export default {
  name: 'UserManage.vue',
  components: {},
  data() {
    var validatePassword = (rule, value, callback) => {
      if (this.operate.opType === 0 && (value === undefined || value === '')) {
        return callback(new Error('密码不能为空'));
      } else {
        callback();
      }
    };

    return {
      fileList: [],
      userList: [],
      roleAllList: [],
      checkRoleList: [1, 2, 3],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        key: ''
      },
      pageResult: {
        total: 0,
        totalPage: 0,
        size: 0,
      },
      dialogFormVisible: false,
      dialogCheckBoxVisible: false,
      formLabelWidth: '120px',
      form: {},
      operate: {
        opType: 0,
        title: ''
      },
      grantRoleParams: {
        userId: 0,
        roleIdList: []
      },
      sexOptions: [
        {
          value: '0',
          label: '男'
        }, {
          value: '1',
          label: '女'
        }
      ],
      userTypeOptions: [
        {
          value: 0,
          label: '学生'
        }, {
          value: 1,
          label: '教师'
        }, {
          value: 2,
          label: '其他'
        }
      ],
      uploadUrl: '/user/add',
      userRules: {
        userName: [
          {required: true, message: '用户名不能为空', trigger: 'blur'}
        ],
        password: [
          {validator: validatePassword, trigger: 'blur'}

        ],
        nickName: [
          {required: true, message: '姓名不能为空', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '邮箱不能为空', trigger: 'blur'}
        ],
        phoneNumber: [
          {required: true, message: '电话不能为空', trigger: 'blur'},
          {max: 11, message: '电话号码长度不能超过11位', trigger: 'blur'}
        ]
      },
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    submitForm(formName, operType) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (operType === 1) {
            this.login();
            return;
          }
          this.registerUser()
        } else {
          return false;
        }
      });
    },
    updateData(user) {
      this.dialogFormVisible = true;
      this.form = JSON.parse(JSON.stringify(user));
      this.form.password = null
      this.operate.opType = 1
      this.operate.title = '编辑用户'
    },
    updateRoleData(user) {
      this.dialogCheckBoxVisible = true;
      this.grantRoleParams.userId = user.userId
      this.grantRoleParams.roleIdList = user.roleIdList === null ? [] : user.roleIdList;

    },
    addData() {
      this.dialogFormVisible = true;
      this.form = {sex: '0', userType: 0, status: '0'};
      this.operate.opType = 0
      this.operate.title = '新增用户'
    },
    deleteData(userId, userType) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(userId, userType)
      }).catch(() => {
        MessageUtil.info('已取消删除')
      });
    },
    getUserList() {
      getUserList(this.pageRequest).then(res => {
        if (res.code === 200) {
          this.userList = res.data.dataList
          this.pageResult.size = res.data.size
          this.pageResult.total = res.data.total
          this.pageResult.totalPage = res.data.totalPage
          if (res.data.size === 0 && res.data.pageNum > 1) {
            this.pageRequest.pageNum--;
            this.getUserList();
          }
        } else {
          MessageUtil.error('用户列表加载失败')
        }
      }).catch(err => {
        MessageUtil.error('用户列表加载失败')
      })
    },
    deleteUser(userId, userType) {
      deleteUser({userId, userType}).then(res => {
        if (res.code === 200) {
          this.getUserList()
          MessageUtil.success('删除成功')
        } else {
          MessageUtil.error(res.message)
        }
      }).catch(err => {
        MessageUtil.error('删除失败')
      })
    },
    async updateUser() {
      let file;
      if (this.fileList.length) {
        file = this.fileList[0].raw
      }
      let form = DeepCopyUtil.copy(this.form);
      if (form.password) {
        form.password = md5(form.password)
      }
      try {
        let res = await updateUser(file, {user: JSON.stringify(form)});
        if (res.code === 200) {
          this.dialogFormVisible = false;
          this.getUserList()
          this.$refs.upload.clearFiles();
          this.fileList = []
          MessageUtil.success('修改成功')
        } else {
          MessageUtil.error(res.message)
        }
      } catch (e) {
        MessageUtil.error('修改失败');
      } finally {
        this.dialogFormVisible = false;
      }
    },
    addUser(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let file;
          if (this.fileList.length) {
            file = this.fileList[0].raw
          }
          let form = DeepCopyUtil.copy(this.form);
          form.password = md5(form.password)
          addUser(file, {user: JSON.stringify(form)}).then(res => {
            if (res.code === 200) {
              this.dialogFormVisible = false;
              this.getUserList()
              this.$refs.upload.clearFiles();
              this.fileList = []
              MessageUtil.success('修改成功')
            } else {
              MessageUtil.error(res.message)
            }
            this.dialogFormVisible = false;
          }).catch(err => {
            MessageUtil.error('修改失败');
          })
          this.dialogFormVisible = false
        } else {
          return false;
        }
      });
    },
    updateUserRole() {
      grantRole(this.grantRoleParams).then(res => {
        if (res.code === 200) {
          this.dialogFormVisible = false;
          this.getUserList()
          MessageUtil.success('角色分配成功')
        } else {
          MessageUtil.error(res.message)
        }
        this.dialogCheckBoxVisible = false
      }).catch(err => {
        MessageUtil.error("角色分配失败")
      })
    },
    getRoleAllList() {
      getRoleAllList().then(res => {
        if (res.code === 200) {
          this.roleAllList = res.data
        }
      }).catch(err => {

      })
    },
    handleChange(file, fileList) {
      // 将上传的文件保存在fileList数组中
      this.fileList = fileList;
    },
    cancel() {
      this.dialogFormVisible = false;
      this.getUserList();
    },
    cancelDialogCheckBox() {
      this.dialogCheckBoxVisible = false;
    },
    formatStatus(row) {
      return row.status === '0' ? '正常' : '禁用'
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleSizeChange(pageSize) {
      console.log(`每页 ${pageSize} 条`);
      this.pageRequest.pageSize = pageSize;
      this.getUserList()
    },
    handleCurrentChange(pageNum) {
      console.log(`当前页: ${pageNum}`);
      this.pageRequest.pageNum = pageNum;
      this.getUserList()
    },
    goBack() {
      window.history.back()
    },
    handleEdit(index, row) {
      console.log(index, row);
    },
    handleDelete(index, row) {
      console.log(index, row);
    },
    resetForm(formName) {
      // 取消校验状态和提示信息
      this.$refs.form.clearValidate();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getUserList();
    this.getRoleAllList()
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
  },
  beforeCreate() {
  },//生命周期 - 创建之前
  beforeMount() {
  }, //生命周期 - 挂载之前
  beforeUpdate() {
  }, //生命周期 - 更新之前
  updated() {
  }, //生命周期 - 更新之后
  beforeDestroy() {
  }, //生命周期 - 销毁之前
  destroyed() {
  }, //生命周期 - 销毁完成
  activated() {
  } //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style scoped>

.header {
  /*display: flex;*/
  /*!*垂直对齐*!*/
  /*align-items: center;*/
  height: 50px;
  background-color: #eff4f9;
}

.page-header {
  float: left;
  margin-top: 15px
}

.search {
  float: right;
  margin-top: 10px
}

.box-card {
  height: 100%;
  padding-bottom: 5px;
}

.block {
  margin-top: 5px;
}

.el-select, .el-input {
  width: 200px
}

.el-form-item {
  width: 330px;
}

</style>
